<template>
  <div class="class-management">
    <!-- 顶部导航栏 -->
    <a-layout-header class="header">
      <div class="header-content">
        <div class="left">
          <img src="/src/assets/image/sztu_icon.webp" alt="SZTU图标" class="sztu-icon" />
          <h1 class="title">离散数学教学辅助系统</h1>
        </div>
        <div class="right">
          <span class="user-info">教师端</span>
          <a-avatar :size="32" icon="user" class="avatar" />
        </div>
      </div>
    </a-layout-header>

    <!-- 主内容区域 -->
    <div class="main-container">
      <!-- 左侧菜单栏 -->
      <div class="sidebar">
        <!-- 返回按钮 -->
        <div class="breadcrumb-bar">
          <a-button type="link" @click="goBack" class="back-btn">
            <LeftOutlined /> 返回班级列表
          </a-button>
        </div>
        <div class="class-name-display">
          <h3>{{ currentClass.name }}</h3>
        </div>
        <a-menu
          v-model:selectedKeys="selectedKeys"
          mode="inline"
          @click="handleMenuClick"
        >
          <a-menu-item key="overview">
            <template #icon>
              <DashboardOutlined />
            </template>
            <span>班级概览</span>
          </a-menu-item>
          <a-menu-item key="students">
            <template #icon>
              <TeamOutlined />
            </template>
            <span>学生管理</span>
          </a-menu-item>
          <a-menu-item key="exercises">
            <template #icon>
              <EditOutlined />
            </template>
            <span>在线练习</span>
          </a-menu-item>
          <a-menu-item key="assignments">
            <template #icon>
              <FileTextOutlined />
            </template>
            <span>作业管理</span>
          </a-menu-item>
          <a-menu-item key="resources">
            <template #icon>
              <FolderOpenOutlined />
            </template>
            <span>资源管理</span>
          </a-menu-item>
        </a-menu>
      </div>

      <!-- 右侧内容区域 -->
      <div class="content">

    <!-- 班级概览 -->
    <div v-show="activeTab === 'overview'" class="tab-content overview-tab">
      <a-row :gutter="16">
        <a-col :span="8">
          <a-card title="班级信息" class="info-card">
            <p><strong>班级名称:</strong> {{ currentClass.name }}</p>
            <p><strong>班级人数:</strong> {{ currentClass.studentCount }}人</p>
            <p><strong>邀请码:</strong> {{ currentClass.inviteCode }}</p>
            <p><strong>创建时间:</strong> {{ currentClass.createTime }}</p>
            <a-button type="primary" @click="showQRCode">生成二维码</a-button>
          </a-card>
        </a-col>
        <a-col :span="16">
          <a-card title="统计数据" class="stats-card">
            <a-row :gutter="16">
              <a-col :span="8">
                <a-statistic title="在线练习数" :value="exerciseStats.count" />
              </a-col>
              <a-col :span="8">
                <a-statistic title="作业布置数" :value="assignmentStats.count" />
              </a-col>
              <a-col :span="8">
                <a-statistic title="资源文件数" :value="resourceStats.count" />
              </a-col>
            </a-row>
            <div class="chart-container">
              <div class="chart-placeholder">学生参与度图表</div>
            </div>
          </a-card>
        </a-col>
      </a-row>
    </div>

    <!-- 学生管理 -->
    <div v-show="activeTab === 'students'" class="tab-content students-tab">
      <a-card title="学生导入">
        <!-- Excel 批量导入 -->
        <div class="import-section">
          <h4>批量导入（Excel）</h4>
          <a-upload
            :beforeUpload="beforeUpload"
            :fileList="fileList"
            @remove="handleRemove"
            accept=".xlsx,.xls"
          >
            <a-button>
              <upload-outlined />
              选择Excel文件
            </a-button>
          </a-upload>
          <a-button 
            type="primary" 
            :disabled="fileList.length === 0" 
            @click="handleImportStudents"
            style="margin-top: 16px;"
          >
            导入学生
          </a-button>
        </div>

        <a-divider />

        <!-- 单个学号导入 -->
        <div class="import-section">
          <h4>通过学号导入</h4>
          <a-form layout="inline" style="margin-top: 12px;">
            <a-form-item label="学号">
              <a-input 
                v-model:value="singleStudentId" 
                placeholder="请输入学号" 
                style="width: 200px;"
                @pressEnter="handleImportSingleStudent"
              />
            </a-form-item>
            <a-form-item>
              <a-button 
                type="primary" 
                :disabled="!singleStudentId" 
                @click="handleImportSingleStudent"
              >
                添加学生
              </a-button>
            </a-form-item>
          </a-form>
        </div>
        
        <a-table 
          :columns="studentColumns" 
          :data-source="studentData" 
          style="margin-top: 20px;"
          :pagination="{ pageSize: 10 }"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'action'">
              <a-button type="link" danger @click="removeStudent(record.id)">移除</a-button>
            </template>
          </template>
        </a-table>
      </a-card>
    </div>

    <!-- 在线练习 -->
    <div v-show="activeTab === 'exercises'" class="tab-content exercises-tab">
      <a-card title="练习设置">
        <a-form :model="exerciseForm" layout="vertical">
          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="练习名称">
                <a-input v-model:value="exerciseForm.name" placeholder="请输入练习名称" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="选择题目">
                <a-select 
                  mode="multiple" 
                  v-model:value="exerciseForm.questions" 
                  placeholder="从题库中选择题目"
                >
                  <a-select-option value="1">命题逻辑基础</a-select-option>
                  <a-select-option value="2">集合运算</a-select-option>
                  <a-select-option value="3">关系与函数</a-select-option>
                  <a-select-option value="4">图论基础</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
          <a-form-item>
            <a-button type="primary" @click="createExercise">创建练习</a-button>
          </a-form-item>
        </a-form>
      </a-card>

      <a-card title="练习列表" style="margin-top: 20px;">
        <a-table 
          :columns="exerciseColumns" 
          :data-source="exerciseData"
          :pagination="{ pageSize: 5 }"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'qrCode'">
              <a-button type="link" @click="generateQRCode(record.link)">生成二维码</a-button>
            </template>
            <template v-if="column.key === 'stats'">
              <a-button type="link" @click="viewExerciseStats(record.id)">查看统计</a-button>
            </template>
            <template v-if="column.key === 'action'">
              <a-button type="link" @click="editExercise(record.id)">编辑</a-button>
              <a-button type="link" danger @click="deleteExercise(record.id)">删除</a-button>
            </template>
          </template>
        </a-table>
      </a-card>
    </div>

    <!-- 作业管理 -->
    <div v-show="activeTab === 'assignments'" class="tab-content assignments-tab">
      <a-card title="发布作业">
        <a-form :model="assignmentForm" layout="vertical">
          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="作业标题">
                <a-input v-model:value="assignmentForm.title" placeholder="请输入作业标题" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="截止日期">
                <a-date-picker v-model:value="assignmentForm.deadline" style="width: 100%" />
              </a-form-item>
            </a-col>
          </a-row>
          <a-form-item label="作业内容">
            <a-textarea 
              v-model:value="assignmentForm.content" 
              placeholder="请输入作业要求或说明" 
              :rows="4" 
            />
          </a-form-item>
          <a-form-item label="附件">
            <a-upload :beforeUpload="beforeAssignmentUpload" :fileList="assignmentFiles">
              <a-button>
                <upload-outlined />
                添加附件
              </a-button>
            </a-upload>
          </a-form-item>
          <a-form-item>
            <a-button type="primary" @click="publishAssignment">发布作业</a-button>
          </a-form-item>
        </a-form>
      </a-card>

      <a-card title="作业列表" style="margin-top: 20px;">
        <a-table 
          :columns="assignmentColumns" 
          :data-source="assignmentData"
          :pagination="{ pageSize: 5 }"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'submissions'">
              <a-button type="link" @click="viewSubmissions(record.id)">
                {{ record.submissionCount }}/{{ currentClass.studentCount }}
              </a-button>
            </template>
            <template v-if="column.key === 'action'">
              <a-button type="link" @click="editAssignment(record.id)">编辑</a-button>
              <a-button type="link" danger @click="deleteAssignment(record.id)">删除</a-button>
            </template>
          </template>
        </a-table>
      </a-card>
    </div>

    <!-- 资源管理 -->
    <div v-show="activeTab === 'resources'" class="tab-content resources-tab">
      <a-card title="上传资源">
        <a-form :model="resourceForm" layout="vertical">
          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="资源名称">
                <a-input v-model:value="resourceForm.name" placeholder="请输入资源名称" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="资源类型">
                <a-select v-model:value="resourceForm.type" placeholder="请选择资源类型">
                  <a-select-option value="courseware">课程课件</a-select-option>
                  <a-select-option value="material">课外资源</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
          <a-form-item label="资源文件">
            <a-upload :beforeUpload="beforeResourceUpload" :fileList="resourceFiles">
              <a-button>
                <upload-outlined />
                选择文件
              </a-button>
            </a-upload>
          </a-form-item>
          <a-form-item>
            <a-button 
              type="primary" 
              :disabled="resourceFiles.length === 0" 
              @click="uploadResource"
            >
              上传资源
            </a-button>
          </a-form-item>
        </a-form>
      </a-card>

      <a-card title="资源列表" style="margin-top: 20px;">
        <a-table 
          :columns="resourceColumns" 
          :data-source="resourceData"
          :pagination="{ pageSize: 5 }"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'action'">
              <a-button type="link" @click="downloadResource(record.id)">下载</a-button>
              <a-button type="link" danger @click="deleteResource(record.id)">删除</a-button>
            </template>
          </template>
        </a-table>
      </a-card>
    </div>

    <!-- 二维码弹窗 -->
    <a-modal
      v-model:open="qrCodeVisible"
      title="班级邀请二维码"
      :footer="null"
      width="300px"
    >
      <div class="qr-code-container">
        <div ref="qrCodeRef" class="qr-code">
          <!-- 使用 QRCode 组件生成二维码 -->
          <img v-if="qrCodeDataUrl" :src="qrCodeDataUrl" alt="QR Code" />
        </div>
        <p class="invite-tip">扫描二维码加入班级</p>
        <p class="invite-code">邀请码: {{ currentClass.inviteCode }}</p>
      </div>
    </a-modal>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { 
  UploadOutlined, 
  LeftOutlined,
  DashboardOutlined,
  TeamOutlined,
  EditOutlined,
  FileTextOutlined,
  FolderOpenOutlined
} from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import QRCode from 'qrcode';
import * as XLSX from 'xlsx';
import { addStudentByCardId } from '../api/auth';

// 获取路由
const router = useRouter();

// 获取路由参数
const route = useRoute();

// 返回班级列表
const goBack = () => {
  router.push('/'); // 返回首页的班级列表
};

// 当前选中的菜单项
const selectedKeys = ref(['overview']);
const activeTab = ref('overview');

// 菜单点击处理
const handleMenuClick = ({ key }) => {
  activeTab.value = key;
};

// 当前班级信息 - 初始化为空对象
const currentClass = reactive({
  id: 1,
  name: '2023级1班',
  studentCount: 32,
  inviteCode: 'DM202301',
  createTime: '2023-09-01'
});

// 统计数据
const exerciseStats = reactive({ count: 5 });
const assignmentStats = reactive({ count: 8 });
const resourceStats = reactive({ count: 12 });

// 学生管理相关
const fileList = ref([]);
const singleStudentId = ref(''); // 单个学号输入
const studentData = ref([
  { id: 1, studentId: '2023001', name: '张三', email: 'zhangsan@example.com' },
  { id: 2, studentId: '2023002', name: '李四', email: 'lisi@example.com' },
  { id: 3, studentId: '2023003', name: '王五', email: 'wangwu@example.com' }
]);

const studentColumns = [
  { title: '学号', dataIndex: 'studentId', key: 'studentId' },
  { title: '姓名', dataIndex: 'name', key: 'name' },
  { title: '邮箱', dataIndex: 'email', key: 'email' },
  { title: '操作', key: 'action' }
];

// 在线练习相关
const exerciseForm = reactive({
  name: '',
  questions: []
});

const exerciseData = ref([
  { id: 1, name: '命题逻辑练习', link: 'https://example.com/exercise/1', createTime: '2023-10-01' },
  { id: 2, name: '集合运算练习', link: 'https://example.com/exercise/2', createTime: '2023-10-05' }
]);

const exerciseColumns = [
  { title: '练习名称', dataIndex: 'name', key: 'name' },
  { title: '题目链接', dataIndex: 'link', key: 'link' },
  { title: '二维码', key: 'qrCode' },
  { title: '统计', key: 'stats' },
  { title: '创建时间', dataIndex: 'createTime', key: 'createTime' },
  { title: '操作', key: 'action' }
];

// 作业管理相关
const assignmentForm = reactive({
  title: '',
  deadline: null,
  content: ''
});

const assignmentFiles = ref([]);
const assignmentData = ref([
  { id: 1, title: '第一章作业', deadline: '2023-10-15', submissionCount: 28 },
  { id: 2, title: '第二章作业', deadline: '2023-10-22', submissionCount: 25 }
]);

const assignmentColumns = [
  { title: '作业标题', dataIndex: 'title', key: 'title' },
  { title: '截止日期', dataIndex: 'deadline', key: 'deadline' },
  { title: '提交情况', key: 'submissions' },
  { title: '操作', key: 'action' }
];

// 资源管理相关
const resourceForm = reactive({
  name: '',
  type: undefined
});

const resourceFiles = ref([]);
const resourceData = ref([
  { id: 1, name: '第一章课件.pdf', type: 'courseware', size: '2.5MB', uploadTime: '2023-09-15' },
  { id: 2, name: '离散数学基础概念.docx', type: 'material', size: '1.2MB', uploadTime: '2023-09-20' }
]);

const resourceColumns = [
  { title: '资源名称', dataIndex: 'name', key: 'name' },
  { title: '类型', dataIndex: 'type', key: 'type' },
  { title: '大小', dataIndex: 'size', key: 'size' },
  { title: '上传时间', dataIndex: 'uploadTime', key: 'uploadTime' },
  { title: '操作', key: 'action' }
];

// 二维码相关
const qrCodeVisible = ref(false);
const qrCodeRef = ref(null);
const qrCodeDataUrl = ref(null); // 存储二维码的 Data URL

// 标签页切换事件
const onTabChange = (key) => {
  console.log('切换到标签页:', key);
};

// 文件上传相关方法
const beforeUpload = (file) => {
  const isExcel = file.type === 'application/vnd.ms-excel' || 
                 file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
  if (!isExcel) {
    message.error('只能上传Excel文件!');
    return false;
  }
  fileList.value = [file];
  return false;
};

const handleRemove = () => {
  fileList.value = [];
};

const handleImportStudents = async () => {
  if (fileList.value.length === 0) {
    message.warning('请选择Excel文件');
    return;
  }

  const file = fileList.value[0];
  const reader = new FileReader();

  reader.onload = async (e) => {
    try {
      // 读取Excel文件
      const data = new Uint8Array(e.target.result);
      const workbook = XLSX.read(data, { type: 'array' });
      
      // 获取第一个工作表
      const firstSheetName = workbook.SheetNames[0];
      const worksheet = workbook.Sheets[firstSheetName];
      
      // 将工作表转换为JSON
      const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
      
      // 提取学号列表(假设学号在第一列,跳过标题行)
      const cardIds = [];
      for (let i = 1; i < jsonData.length; i++) {
        if (jsonData[i][0]) {
          cardIds.push(String(jsonData[i][0]).trim());
        }
      }
      
      if (cardIds.length === 0) {
        message.warning('Excel文件中没有找到有效的学号');
        return;
      }
      
      // 调用后端API导入学生
      const result = await addStudentByCardId(currentClass.id.toString(), cardIds);
      
      if (result.code === 1) {
        message.success(`成功导入 ${cardIds.length} 个学生`);
        fileList.value = [];
        // TODO: 刷新学生列表
      } else {
        message.error(result.msg || '导入失败');
      }
    } catch (error) {
      console.error('Excel解析失败:', error);
      message.error('Excel文件解析失败,请检查文件格式');
    }
  };

  reader.readAsArrayBuffer(file);
};

// 单个学号导入
const handleImportSingleStudent = async () => {
  if (!singleStudentId.value.trim()) {
    message.warning('请输入学号');
    return;
  }
  
  // 检查学号是否已存在(可选,也可以让后端处理)
  const exists = studentData.value.some(student => student.studentId === singleStudentId.value.trim());
  if (exists) {
    message.warning('该学号已存在');
    return;
  }
  
  try {
    // 调用后端API添加学生(单个学号也是数组形式)
    const result = await addStudentByCardId(
      currentClass.id.toString(), 
      [singleStudentId.value.trim()]
    );
    
    if (result.code === 1) {
      message.success(`学生 ${singleStudentId.value} 添加成功`);
      singleStudentId.value = ''; // 清空输入
      // TODO: 刷新学生列表
    } else {
      message.error(result.msg || '添加失败');
    }
  } catch (error) {
    console.error('添加学生失败:', error);
    message.error('添加学生失败,请稍后重试');
  }
};

const removeStudent = (id) => {
  message.success('学生移除成功');
};

// 在线练习相关方法
const createExercise = () => {
  if (!exerciseForm.name) {
    message.warning('请输入练习名称');
    return;
  }
  message.success('练习创建成功');
  exerciseForm.name = '';
  exerciseForm.questions = [];
};

// 生成二维码的方法
const generateQRCode = async (link) => {
  try {
    // 生成二维码的 Data URL
    const dataUrl = await QRCode.toDataURL(link);
    qrCodeDataUrl.value = dataUrl;
    qrCodeVisible.value = true;
  } catch (error) {
    console.error('生成二维码失败:', error);
    message.error('生成二维码失败');
  }
};

// 为班级邀请生成二维码
const showQRCode = async () => {
  try {
    // 生成班级邀请链接的二维码
    const inviteLink = `${window.location.origin}/join-class/${currentClass.inviteCode}`;
    const dataUrl = await QRCode.toDataURL(inviteLink);
    qrCodeDataUrl.value = dataUrl;
    qrCodeVisible.value = true;
  } catch (error) {
    console.error('生成二维码失败:', error);
    message.error('生成二维码失败');
  }
};

const viewExerciseStats = (id) => {
  message.info(`查看练习${id}的统计数据`);
};

const editExercise = (id) => {
  message.info(`编辑练习${id}`);
};

const deleteExercise = (id) => {
  message.success(`练习${id}已删除`);
};

// 作业管理相关方法
const beforeAssignmentUpload = (file) => {
  assignmentFiles.value = [file];
  return false;
};

const publishAssignment = () => {
  if (!assignmentForm.title) {
    message.warning('请输入作业标题');
    return;
  }
  message.success('作业发布成功');
  assignmentForm.title = '';
  assignmentForm.deadline = null;
  assignmentForm.content = '';
  assignmentFiles.value = [];
};

const viewSubmissions = (id) => {
  message.info(`查看作业${id}的提交情况`);
};

const editAssignment = (id) => {
  message.info(`编辑作业${id}`);
};

const deleteAssignment = (id) => {
  message.success(`作业${id}已删除`);
};

// 资源管理相关方法
const beforeResourceUpload = (file) => {
  resourceFiles.value = [file];
  return false;
};

const uploadResource = () => {
  if (!resourceForm.name || !resourceForm.type) {
    message.warning('请填写完整资源信息');
    return;
  }
  message.success('资源上传成功');
  resourceForm.name = '';
  resourceForm.type = undefined;
  resourceFiles.value = [];
};

const downloadResource = (id) => {
  message.info(`下载资源${id}`);
};

const deleteResource = (id) => {
  message.success(`资源${id}已删除`);
};

// 当组件加载时，根据路由参数设置当前班级信息
onMounted(() => {
  const classId = route.params.id;
  console.log('当前班级ID:', classId);
  // 在实际应用中，这里会根据班级ID从后端获取班级详细信息
  // 这里我们只是演示，所以使用模拟数据
});
</script>

<style scoped>
.class-management {
  min-height: 100vh;
  background-color: #fafafa;
}

/* 顶部导航栏样式 */
.header {
  background: #fff;
  padding: 0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
  height: 100px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 24px;
  height: 100%;
}

.left {
  display: flex;
  align-items: center;
}

.sztu-icon {
  width: 80px;
  height: 80px;
  margin-right: 16px;
}

.title {
  color: #003366;
  font-size: 2rem;
  font-weight: 700;
  margin: 0;
  font-family: 'Segoe Script', 'Brush Script MT', cursive;
}

.right {
  display: flex;
  align-items: center;
}

.user-info {
  margin-right: 12px;
  color: rgba(0, 0, 0, 0.65);
}

.avatar {
  background-color: #1890ff;
}

/* 主容器样式 */
.main-container {
  display: flex;
  margin-top: 100px;
  height: calc(100vh - 100px);
  position: relative;
}

/* 左侧菜单栏 */
.sidebar {
  width: 250px;
  background-color: #ffffff;
  border-right: 1px solid #e0e0e0;
  flex-shrink: 0;
  position: fixed;
  top: 100px;
  left: 0;
  bottom: 0;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
}

/* 面包屑导航栏 */
.breadcrumb-bar {
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
}

.back-btn {
  padding: 0;
  font-size: 14px;
}

/* 班级名称显示 */
.class-name-display {
  padding: 16px 24px;
  border-bottom: 1px solid #f0f0f0;
}

.class-name-display h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #003366;
}

/* 右侧内容区域 */
.content {
  flex: 1;
  padding: 20px;
  background-color: #fafafa;
  overflow-y: auto;
  margin-left: 250px;
}

.tab-content {
  margin-top: 20px;
}

.info-card,
.stats-card {
  height: 100%;
}

.chart-container {
  margin-top: 20px;
  height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.chart-placeholder {
  width: 100%;
  height: 100%;
  background-color: #f0f2f5;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
}

.qr-code-container {
  text-align: center;
}

.qr-code {
  margin: 0 auto;
  width: 200px;
  height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.qr-code img {
  max-width: 100%;
  max-height: 100%;
}

.invite-tip {
  margin: 10px 0;
  font-weight: bold;
}

.invite-code {
  font-family: monospace;
  background-color: #f0f0f0;
  padding: 4px 8px;
  border-radius: 4px;
  display: inline-block;
}

/* 学生导入区域样式 */
.import-section {
  margin-bottom: 16px;
}

.import-section h4 {
  margin-bottom: 12px;
  color: #003366;
  font-weight: 600;
}

/* 标签页内容区域 */
.tab-content {
  margin-top: 0;
}

/* 卡片样式优化 */
.content :deep(.ant-card) {
  margin-bottom: 20px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.03);
}
</style>